﻿module Parser
open CLexer
open Tokens
open Grammar
open Yard.Generators.RACCGenerator
open Translate

(*
let is_brace = function 
        | Tokens.LBRACE _ | Tokens.RBRACE _ | Tokens.LPAREN _ | Tokens.RPAREN _ -> true
        | _ -> false
let toGrammarToken = function
    | Tokens.LBRACE _ -> Grammar.LBRACE
    | Tokens.RBRACE _ -> Grammar.RBRACE
    | Tokens.LPAREN _ -> Grammar.LPAREN
    | Tokens.RPAREN _ -> Grammar.RPAREN
    | _ ->  Grammar.EOF
*)

//let emptyLexeme = {name = "";value ="*"}
//let eofLexeme = {emptyLexeme with name = "EOF"}

let Run inName = 
        let start = System.DateTime.Now
        printfn "Start"
        let lexer = CLexer.init inName
        try
            let result =
                lexer
                |> Grammar.file
                    (fun p ->
                        let res = ref (CLexer.initial p)
    //                    while (!res <> Tokens.EOF) do
      //                      res := CLexer.initial p
                        !res |> toGrammarToken
                    )
            let timeAfterWork = System.DateTime.Now
            printfn "Time to work:%A" (timeAfterWork - start)
            result
        with e -> // when e.Message="parse error" -> 
            let pos = lexer.EndPos
            let extendedMessage = sprintf "error near line %d, character %d\nlast token: %s\n\n%s" pos.pos_lnum (pos.pos_cnum - pos.pos_bol) (new System.String(lexer.Lexeme)) (e.ToString())
            failwith extendedMessage
    
